package com.retailers.generator.service.Impl;

import com.retailers.generator.config.Genconfig;
import com.retailers.generator.service.CodeGeneraeService;
import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils;
import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.NullCacheStorage;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.*;
import java.util.Map;

/**
 * @description:
 * @author: honglei
 * @time: 2021/3/23 0023 14:10
 */
@Service
public class CodeServiceImpl implements CodeGeneraeService {
    private static final Configuration CONFIGURATION = new Configuration(Configuration.VERSION_2_3_22);


    @PostConstruct
    public void initTemplate() {
        //这里比较重要，用来指定加载模板所在的路径
        CONFIGURATION.setTemplateLoader(new ClassTemplateLoader(CodeServiceImpl.class, "/templates/mybatis-plus"));
        CONFIGURATION.setDefaultEncoding("UTF-8");
        CONFIGURATION.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        CONFIGURATION.setCacheStorage(NullCacheStorage.INSTANCE);
    }
    public  Template getTemplate(String templateName) throws IOException {
        try {
            return CONFIGURATION.getTemplate(templateName);
        } catch (IOException e) {
            throw e;
        }
    }

    public  void clearCache() {
        CONFIGURATION.clearTemplateCache();
    }

    @Override
    public boolean generateFileByTemplate(String templateName, File file, Map<String, Object> dataMap) throws Exception {
        if (!file.exists()){
            FileUtils.forceMkdirParent(file);
        }
        FileOutputStream fos = new FileOutputStream(file);
        Writer out = new BufferedWriter(new OutputStreamWriter(fos, "utf-8"),10240);
        getTemplate(templateName).process(dataMap,out);
        return true;
    }

    @Override
    public boolean generateFileByTemplate(String templateName, String filePath, Map<String, Object> dataMap) throws Exception {

        return false;
    }


}
